package com.infinitus.nginxInfo;


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.infinitus.nginxInfo.config.KafkaConfig;
import com.infinitus.nginxInfo.config.RedisKeyConfig;
import com.infinitus.nginxInfo.service.RedisService;
import com.infinitus.nginxInfo.service.util.Base64Coder;
import com.infinitus.nginxInfo.task.Cleaner;


@SpringBootApplication 
@EnableTransactionManagement
@EnableAsync
@RestController
@EnableAutoConfiguration
@EnableScheduling
@ComponentScan(basePackages={"com.infinitus.nginxInfo.*"})
@ImportResource("classpath:disconf.xml") 
@RequestMapping("/root")
public class App extends SpringBootServletInitializer{
	@Resource(name = "redisServiceDB0") 
    private RedisService redisService0;
	
	@Resource(name = "redisServiceDB2") 
	private RedisService redisService2;
	
	@Autowired
	private KafkaConfig kafkaConfig;
	
	@RequestMapping(value="/getUserDecryKey", method={ RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object getUserDecryKey(){
		return kafkaConfig.getUserDecryKey();
	}
	
	
	@RequestMapping(value="/testCache", method={ RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public void testCache(String data){
		System.out.println(redisService0.get("123").toString());
		redisService2.set("0test", data);
	}
	
	@RequestMapping("/h")
	@Cacheable(value = "function", keyGenerator = "keyGenerator")
	public String getSessionId(HttpSession session) {
		redisService0.set("123", "测试");
		System.out.println("进入了方法");
		String string = redisService0.get("123").toString();
		return string;
	}
	
	@RequestMapping("/g")
	public String getCacheId(HttpSession session) {
		String test = UUID.randomUUID().toString();
		redisService0.set(test, "");
		String string = redisService0.get(test).toString();
		return string;
	}
	
	@RequestMapping("/stopPoll")
	public Boolean stopPoll(String password) {
		if(password !=null && "dXNlcmJlaGF2aW9y".equals(Base64Coder.encodeString(password))){
			Cleaner.SHUTDOWN=true;
		}
		return Cleaner.SHUTDOWN;
	}
	
	@RequestMapping("/record/cacheDeviceId")
	public Object cacheDeviceId() throws IOException {
		BufferedReader octReader  = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\deviceid.txt"),"utf-8"));
		HashSet<String> deviceids = new HashSet<String>();
		String detailStr = null;
		while((detailStr = octReader.readLine())!=null){
			String[] detailArr = detailStr.split("\",\"");
			deviceids.addAll(Arrays.asList(detailArr));
		}
		octReader.close();
		for(String deviceId: deviceids){
			if(deviceId.matches("^[a-zA-Z0-9\\-\\_]+$")){
				String newUserSign = RedisKeyConfig.EXISTS_DEVICEID+deviceId;
				if(!redisService0.exists(newUserSign)){
					redisService0.set(newUserSign, "", 240*24*60*60*1000l);
				}
			}
		}
		System.out.println(deviceids.size());
		Set<Serializable> keys = redisService0.keys( RedisKeyConfig.EXISTS_DEVICEID+"*");
		return  keys.size();
	}
	
	 /* @Bean  
    public FilterRegistrationBean  filterRegistrationBean() {  
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();  
        CatFilter cf = new CatFilter();
        registrationBean.setFilter(cf);  
        List<String> urlPatterns = new ArrayList<String>();  
        urlPatterns.add("/*");  
        registrationBean.setUrlPatterns(urlPatterns);  
        return registrationBean;  
    }  */
	public static void main(String[] args) {
		System.out.println("---NginxInfo STARTUP---");
		final ConfigurableApplicationContext applicationContext = SpringApplication.run(App.class, args);
		/*final CrashLogCleaner crashLogCleaner = new CrashLogCleaner(applicationContext);
		final UserbehaviorCleaner userbehaviorCleaner = new UserbehaviorCleaner(applicationContext);
		crashLogCleaner.start();
		userbehaviorCleaner.start();*/
		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				Cleaner.SHUTDOWN=true;
				try {
					Thread.sleep(20000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("offset提交完成");
				if(applicationContext!=null){
					applicationContext.stop();
					applicationContext.close();
				}
			}
		});
	}
	
	@Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(App.class);
    }

}
